package http

import (
	"net/http"
	"time"
)

// HTTPChecker HTTP端口检测参数结构体
// URL: 检测目标URL
// Timeout: 超时时间（秒）
// Method: 请求方法（GET/POST等）
type HTTPChecker struct {
	URL     string
	Timeout int
	Method  string
}

// HTTPCheckResult 检测结果
// Success: 是否检测成功
// StatusCode: 实际响应码
// Err: 错误信息
type HTTPCheckResult struct {
	Success    bool
	StatusCode int
	Err        error
}

// NewHTTPChecker 创建HTTPChecker实例
func NewHTTPChecker(url string, timeout int, method string) *HTTPChecker {
	if timeout <= 0 {
		timeout = 5
	}
	if method == "" {
		method = "GET"
	}
	return &HTTPChecker{
		URL:     url,
		Timeout: timeout,
		Method:  method,
	}
}

// Check 检测HTTP端口及响应码，expectCode为期望的HTTP响应码
func (hc *HTTPChecker) Check(expectCode int) *HTTPCheckResult {
	client := &http.Client{
		Timeout: time.Duration(hc.Timeout) * time.Second,
	}
	req, err := http.NewRequest(hc.Method, hc.URL, nil)
	if err != nil {
		return &HTTPCheckResult{Success: false, StatusCode: 0, Err: err}
	}
	resp, err := client.Do(req)
	if err != nil {
		return &HTTPCheckResult{Success: false, StatusCode: 0, Err: err}
	}
	defer resp.Body.Close()
	success := resp.StatusCode == expectCode
	return &HTTPCheckResult{
		Success:    success,
		StatusCode: resp.StatusCode,
		Err:        nil,
	}
}

// CheckConnOnly 仅检测HTTP端口是否能连接，不判断响应码
func (hc *HTTPChecker) CheckConnOnly() *HTTPCheckResult {
	client := &http.Client{
		Timeout: time.Duration(hc.Timeout) * time.Second,
	}
	req, err := http.NewRequest(hc.Method, hc.URL, nil)
	if err != nil {
		return &HTTPCheckResult{Success: false, StatusCode: 0, Err: err}
	}
	resp, err := client.Do(req)
	if err != nil {
		return &HTTPCheckResult{Success: false, StatusCode: 0, Err: err}
	}
	defer resp.Body.Close()
	return &HTTPCheckResult{
		Success:    true,
		StatusCode: resp.StatusCode,
		Err:        nil,
	}
}
